package com.tt.plat8.bootstrap;

import org.osgi.framework.Bundle;
import org.osgi.service.http.HttpContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * UserBean: tangtao
 * Date: 14-1-21
 * Time: 下午3:06
 * To change this template use File | Settings | File Templates.
 */
public class ResourceProvider implements HttpContext {
    private List<Bundle> resources = new ArrayList();

    public static final String RESOURCE_BASE = "/VAADIN";

    @Override
    public boolean handleSecurity(HttpServletRequest request, HttpServletResponse httpServletResponse) throws IOException {
        return true;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public URL getResource(String uri) {
        URL resource = null;
        // iterate over the vaadin bundles and try
        // to find the requested resource
        for (Bundle bundle : resources) {
            resource = bundle.getResource(uri);
            if (resource != null) {
                break;
            }
        }
        return resource;
    }

    @Override
    public String getMimeType(String file) {

        if(file.endsWith(".jpg")){
            return "image/jpeg";
        }else if(file.endsWith(".png")){
            return "image/png";
        } else{
            return "text/html";
        }

    }

    /**
     * 20     * Adds a bundle that may potentially contain
     * 21     * a requested resource.
     * 22     * @param bundle
     * 23
     */
    public void add(Bundle bundle) {
        resources.add(bundle);
    }

    /**
     * Removes a bundle that may potentially contain
     * a requested resource.
     *
     * @param bundle
     */
    public void remove(Bundle bundle) {
        resources.remove(bundle);
    }
}
